{extend name="base"/}
{block name="resources"}
<style>
	.ns-form {margin-top: 0;}
	.coupon-box{
		padding: 20px;
	}

	.coupon-box .layui-form{
		padding: 0!important;
	}

	.layui-layer-page .layui-layer-content{
		overflow: auto !important;
	}

	.ns-del-btn {
		cursor: pointer;
	}

	.ns-level-equity .layui-input {
		display: inline-block;
	}

	.gods-box table:first-of-type{
		margin-bottom: 0;
	}
	.gods-box table:last-of-type{
		margin-top: 0;
		display: block;
		max-height: 323px;
		overflow: auto;
	}
	.coupon-box .ns-single-filter-box{
		padding-top: 0;
	}
	.colorSelector{
		position: relative;
	    width: 20px;
	    height: 20px;
	    border-radius: 3px;
	    border: 1px solid #d7d7d7;
	    display: inline-block;
    	cursor: pointer;
    	vertical-align: middle;
	    padding: 2px;
	}
	.colorSelector div{
		width: 100%;
		height: 100%;
		border-radius: 3px;
	}
	.flexbox-fix-btn .btn{
		margin-top: 0;
		line-height: 1;
	}
</style>
{/block}
{block name="main"}
<div class="layui-form">


	<div class="layui-card ns-card-common ns-card-brief ns-level-equity">
		<!--<div class="layui-card-header">
			<span class="ns-card-title">权益描述</span>
		</div>-->

		<div class="layui-form-item">
			<label class="layui-form-label">一级说明：</label>
			<div class="layui-input-block">
				<textarea name="first_remark" class="layui-textarea ns-len-long">{$level_info.first_remark}</textarea>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">二级说明：</label>
			<div class="layui-input-block">
				<textarea name="second_remark" class="layui-textarea ns-len-long">{$level_info.second_remark}</textarea>
			</div>
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">详情描述：</label>
			<!--<div class="layui-input-block ns-len-long">
				<textarea name="remark" class="layui-textarea"></textarea>
			</div>-->
			<div class="layui-input-inline">
				<script id="editor3" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
			<input type="hidden" name="" id="remark" value="{$level_info.remark}" />
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">一级内容描述：</label>
			<div class="layui-input-inline">
				<script id="editor" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
			<input type="hidden" name="" id="first_content_description" value="{$level_info.first_content_description}" />
		</div>

		<div class="layui-form-item">
			<label class="layui-form-label">二级内容描述：</label>
			<div class="layui-input-inline">
				<script id="editor2" type="text/plain" class="ns-special-length" style="height:300px;"></script>
			</div>
			<input type="hidden" name="" id="second_content_description" value="{$level_info.second_content_description}" />
		</div>
	</div>


	<input type="hidden" name="level_id" value="{$level_info.level_id}">
	
	<div class="layui-card ns-card-common">
		<div class="layui-card-body">
			<div class="ns-form-row">
				<button class="layui-btn ns-bg-color" lay-submit lay-filter="save">保存</button>

			</div>
		</div>
	</div>
</div>


{/block}
{block name="script"}
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.config.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/ueditor.all.js"></script>
<script type="text/javascript" charset="utf-8" src="STATIC_EXT/ueditor/lang/zh-cn/zh-cn.js"></script>
<script>
	var coupon_list = '';
    var coupon_id = [], addCoupon;
	var form , laytpl;

	var ue = UE.getEditor('editor');
	if($("#first_content_description").val()){
		ue.ready(function() {
			ue.setContent($("#first_content_description").val());
		});
	}

	var ue2 = UE.getEditor('editor2');
	if($("#second_content_description").val()){
		ue2.ready(function() {
			ue2.setContent($("#second_content_description").val());
		});
	}

	var ue3 = UE.getEditor('editor3');
	if($("#remark").val()){
		ue3.ready(function() {
			ue3.setContent($("#remark").val());
		});
	}

	layui.use(['form', 'laytpl'], function() {
		form = layui.form;
		laytpl = layui.laytpl,
			repeat_flag = false; //防重复标识
		form.render();


		var upload = new Upload({
			elem: '#storeUpload'
		});
		/**
		 * 监听保存
		 */
		form.on('submit(save)', function(data) {
			data.field.bg_color = $('#color-picker').attr('data-value');
            data.field.send_coupon = coupon_id.toString();
			if(repeat_flag) return false;

			/*let level = {};
			$('#level-rule tr').each(function (i, e) {
				if($(e).find('.price').val() != undefined){
					level[$(e).find('select').val()] = $(e).find('.price').val();
				}
				/!*if($(e).find('.market_price').val() != undefined){
					level[$(e).find('select').val()] = $(e).find('.market_price').val();
				}*!/
			})
			if(JSON.stringify(level) == '{}'){
				layer.msg('请设置付费规则');
				return false;
			}*/

			data.field.first_content_description = ue.getContent();
			data.field.second_content_description = ue2.getContent();
			data.field.remark = ue3.getContent();

			if(!data.field.cover) upload.delete();
			data.field.send_coupon = coupon_list;

			//data.field.charge_rule = JSON.stringify(level);
			repeat_flag = true;
			$.ajax({
				url: ns.url("admin/membercard/edit"),
				data: data.field,
				type: "POST",
				dataType: "JSON",
				success: function(res) {
					repeat_flag = false;
					if (res.code == 0) {
						location.reload();
					}
				}
			});
		});
		
		/**
		 * 表单验证
		 */
		form.verify({
			num: function(value) {
				var arrMen = value.split(".");
				var val = 0;
				if (arrMen.length == 2) {
					val = arrMen[1];
				}
				
				if (value == "") {
					return false;
				}
				if (value < 0 || val.length > 2) {
					return '请输入大于等于0的数，保留小数点后两位'
				}
			},
			fl: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

            	if (isNaN(parseFloat(value))) {
                	return  "请设置" + str;
                }

                if (value <= 0) {
                    return str + "不能小于等于0";
                }

                if (value > 100) {
                    return str + "不能大于100";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            },
            jf: function(value, item) {
                var str = $(item).parents(".layui-form-item").find("label").text().split("*").join("");
                str = str.substring(0, str.length - 1);

                if (value < 0) {
                    return str + "不能小于0";
                }

                if (value > 100) {
                    return str + "不能大于100";
                }

                var arrMen = value.split(".");
                var val = 0;
                if (arrMen.length == 2) {
                    val = arrMen[1];
                }
                if (val.length > 2) {
                    return str + "最多可保留两位小数";
                }
            }

		});


	});

	$('body').on('click', '.coupon .select-coupon', function(e){
		var event = this;

		layer.open({
			type: 1,
			area: ["950px","600px"],
			title: '优惠券列表',
			skin: 'select-coupon-layer',
			content: $("#couponList").html()
		});

		couponTable = new Table({
			elem: "#coupon_list",
			url: ns.url("platformcoupon://admin/platformcoupon/lists"),
			where: {'status': 1,'type':1},
			cols: [
				[{
					title: '优惠券名称',
					unresize: 'false',
					width: '20%',
					templet: '#couponName'
				}, {
					title: '优惠内容',
					unresize: 'false',
					width: '20%',
					templet: function(data){
						return data.at_least > 0 ? '满' +data.at_least+ '减' +data.money : '无门槛，减' +data.money
					}
				},{
					field: 'gift_state',
					title: '有效期限',
					unresize: 'false',
					width: '30%',
					templet: function (res) {
						if(res.validity_type == 0){
							return "有效时间至" + ns.time_to_date(res.end_time);
						}else{
							return "有效时间" + res.fixed_term + "天";
						}
					}
				}, {
					title: '操作',
					toolbar: '#couponOperation',
					unresize: 'false',
					align: 'center',
					width: '20%'
				}]
			]
		});

		couponTable.tool(function(obj) {
			var data = obj.data;
			switch (obj.event) {
				case "add":
					addcoupon(data);
					break;
			}
		});

		function addcoupon(data){
			var template = `<tr data-coupon="{{ d.platformcoupon_type_id }}">
				<td>{{ d.platformcoupon_name }}</td>
				{{# if(d.at_least > 0){  }}
					<td>满{{ d.at_least }}{{ '减' + d.money }}</td>
				{{# } else { }}
					<td>无门槛，{{'减' + d.money }}</td>
				{{# } }}
				<td style="text-align:center;"><a href="javascript:;" onclick="deleteCoupon(this)" class="ns-text-color">删除</a></td>
			</tr>`;
			laytpl(template).render(data, function(string){
				$(event).parents('.discount-cont').find('.layui-table tbody').append(string);
				layer.closeAll();
			});
			getCoupon();
		}
	})

	// 删除优惠券
	function deleteCoupon(e){
		$(e).parents('tr').remove();
		getCoupon();
	}
	getCoupon();
	//获取已选中优惠券
	function getCoupon() {
		var coupon = [];

		$('.coupon').find('tr[data-coupon]').each(function (i, e) {
			coupon.push($(e).attr('data-coupon'));
		})

		coupon_list = coupon.toString();
	}

    function back(){
		location.href = ns.url("supermember://admin/membercard/lists");
	}

	//添加付费规则
	function addRule() {
		let level_select = {:json_encode($level_time, JSON_UNESCAPED_UNICODE)};;
		$('#level-rule tr').each(function (i, e) {
			if($(e).find('select').val() && $(e).find('select').val() != undefined){
				delete level_select[$(e).find('select').val()];
			}
		})

		var select_html = '';
		for (let i in level_select){
			select_html += '<option value="'+i+'">'+level_select[i]+'</option>';
		}

		var html = `
			<tr>
				<td>
					<div class="ns-len-short">
						<select lay-filter="selectRule">
							${select_html}
						</select>
					</div>
				</td>
				<td class="align-center">
					<input  type="text" value="0" lay-verify="num" class="layui-input ns-len-short price" placeholder="价格/元">
				</td>
				<td>
					<a href="javascript:void(0)" class="ns-text-color" onclick="deleteRule(this)">删除</a>
				</td>
			</tr>
		`;

		$('#level-rule tbody').append(html);
		if($('#level-rule tr').length == 5){
			$('#add_rule_btn').hide()
		}
		form.render();
		form.on('select(selectRule)', function(data){
			let num = 0;
			$('#level-rule tr').each(function (i, e) {
				if($(e).find('select').val() == data.value){
					num++;
					$('.delete-rule').removeClass('delete-rule');
					$(e).find('select').addClass('delete-rule');
				}
			})
			if(num > 1) deleteRule($('.delete-rule'));
		});

		form.verify({
			num: function (value) {

				var arrmen = value.split(".");
				var val = 0;
				if (arrmen.length == 2) {
					val = arrmen[1];
				}

				if (value == "") {
					return false;
				}
				if (value < 0 || val.length > 2) {
					return '请输入大于等于0的数，保留小数点后两位'
				}
			}
		})

		return false;
	}

	function deleteRule(obj) {
		$(obj).parents('tr').remove();
		if($('#level-rule tr').length < 5){
			$('#add_rule_btn').show()
		}
	}

</script>


{/block}